<template>
  <div class="room">
    <!-- 显示当前在线人数 -->
    <div>目前在线人数：{{ onLineNum }}</div>
    <!-- 消息列表容器，用于显示聊天记录 -->
    <div class="view" ref="scrollContainer">
      <div v-for="item in messageList">
        <!-- 系统通知消息 -->
        <div class="notice" v-if="item.id === 0">{{ item.message }}</div>
        <!-- 其他用户的消息 -->
        <div class="other" v-else-if="item.id !== user.id">
          <div class="hImg" v-if="item.imageUrl">
            <img style="border-radius: 6px;" :src="item.imageUrl" @error="setDefaultImage($event)">
          </div>
          <div>
            <p style="margin-left: 10px; font-size: smaller;">{{ item.name }}</p>
            <div class="message">{{ item.message }}
              <!-- 添加播放按钮 -->
              <el-button style="width: 20px;height: 20px;margin: 0 0 0 5px;"
              link
               @click="playSpeech(item.message)"
               :icon="VideoPlay"
               class="play-btn"
              />
              <span>{{ item.createTime }}</span>
            </div>
            
            
          </div>
        </div>
        <!-- 当前用户的消息 -->
        <div class="me" v-else>
          <div>
            <p style="font-size: smaller; text-align: right; margin-right: 10px;">{{ item.name }}</p>
            <div class="message">{{ item.message }}</div>
          </div>
          <div class="hImg">
            <img style="border-radius: 6px;" :src="item.imageUrl">
          </div>
        </div>
      </div>
    </div>
    <div class="aite">
      <span v-for="item in aiteItem" class="aiteItem" @click="openAI(item.name)">{{ item.name }}</span>
    </div>
    <!-- 输入框和发送按钮 -->
    <div class="input">
      <el-input type="textarea" placeholder="请输入..." :autosize="{ minRows: 7, maxRows: 7 }" resize="none" style="width: 100%; float: left;" v-model.trim="input" @keyup.enter="send(input,1)"/>
        <el-tooltip
          effect="dark"
          content="发送"
          placement="top"
        >
          <el-button class="input-anniu" @click="send(input,1)">
            <el-icon><Position /></el-icon>
          </el-button>
        </el-tooltip>
        <el-tooltip
          effect="dark"
          :content="tooltipContent"
          placement="top"
        >
          <el-button  class="input-anniu" @click="toggleVoice">
            <el-icon>
              <component :is="recordingIcon" />
            </el-icon>
          </el-button>
        </el-tooltip>

    </div>

    
    <div v-if="isRecording && !isPaused" class="recording-animation">
      正在 <br> 识别
    </div>
  <!-- <div  class="bo" v-if="bo">
      <div ref="recwave" style="height: 100%; width: 100%"></div>
  </div> -->

  <el-dialog destroy-on-close class="custom-dialog" top="2%" v-model="AIDialog" style="height: 90%;position: relative;padding: 0;" :show-close="false">
    <AIChat @custom-event="send" :AIMessageList="AIMessageList" :user="user"></AIChat>
  </el-dialog>
  </div>


</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, onUpdated,markRaw } from 'vue'
import useCounter from '../../stores/pinia'
import { getAllGroupMessageAPI} from '../../api/message'
import { ElNotification } from 'element-plus'
import { useRouter } from 'vue-router';
import { parseJwt } from '../../stores/pinia';
// import { startRecording,stopRecording } from './js/toText';
// import Recorder from 'recorder-core';
//   import 'recorder-core/src/engine/mp3';
//   import 'recorder-core/src/engine/mp3-engine';
//   import 'recorder-core/src/engine/wav';
//   import 'recorder-core/src/extensions/waveview';
  import { VideoPlay,Microphone, Mic,Position } from '@element-plus/icons-vue'
  import{playSpeech,initSpeech} from '../forum/js/voice'
  import AIChat from './AIChat.vue';

  const AIDialog=ref(false)
  const bo=ref(false)
// 输入框绑定的值
const input = ref('')
// 路由对象
const router = useRouter()
// 消息列表
const messageList = ref([])
// 当前用户信息
const user = ref({
  id: null,
  name: '',
  imageUrl: 'https://www.toopic.cn/public/uploads/small/169139790585716913979057.jpg'
})
const AIMessageList = ref([{ id: "1", message: "等你好久了"+user.value.name+"，终于来找我聊天了",imageUrl:"https:////web-tlias-lkc.oss-cn-beijing.aliyuncs.com/2025-03-16-14-57-40-570ac3d2082c4557bada5e7cd190da4c.jpeg" }])
// Pinia存储对象
const counterStore = useCounter()
// WebSocket对象
const websocket = ref(null)
// 在线人数
const onLineNum = ref(0)
const aiteItem=ref([
  {
    id:1,
    name:"@AI助手",

  },
])
// WebSocket连接状态
const wsStatus = ref(WebSocket.CLOSED)

// 初始化WebSocket连接
const login = () => {
  if ('WebSocket' in window&&counterStore.jwt) {
    // websocket.value = new WebSocket(`ws://8.134.66.229:8024/web-socket/${user.value.id}`)
    websocket.value = new WebSocket(`ws://localhost:8024/web-socket/${user.value.id}`)
    websocket.value.onerror = () => {
      ElNotification.error('连接发生错误')
      wsStatus.value = WebSocket.CLOSED
    }
    websocket.value.onopen = () => {
      ElNotification.success('websocket连接成功')
      wsStatus.value = WebSocket.OPEN
    }
    websocket.value.onmessage = (event) => {
      const data = JSON.parse(event.data)
      // console.log("后端数据",data)
      if (data && typeof data === 'object') {
        if(data.type===1){
          // console.log("fewfew")
          messageList.value.push(data)
        }else if(data.type==="3"){
          // console.log("dd得瑟得瑟",AIMessageList.value)
          AIMessageList.value.push(data)
        }
      } else {
        console.error('接收到的消息格式不正确', data)
      }
    }
    websocket.value.onclose = () => {
      ElNotification.warning('websocket连接关闭')
      wsStatus.value = WebSocket.CLOSED
    }
  } else {
    ElNotification.error('当前浏览器不支持WebSocket')
  }
}

// 设置在线人数
const setOnlineNum = (num) => {
  onLineNum.value = num
  // console.log(onLineNum.value)
}

// 暴露在线人数给父组件或其他组件使用
defineExpose({ onLineNum })

// 获取滚动容器引用
const scrollContainer = ref(null)

// 滚动到底部
const scrollToBottom = () => {
  if (scrollContainer.value) {
    scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight
  }
}

const openAI=(name)=>{
  AIDialog.value=true
}

// 发送消息
const send = (inputText,type) => {
    if (!websocket.value || websocket.value.readyState !== WebSocket.OPEN) {
      ElNotification.error('WebSocket连接未建立，请检查网络设置或刷新一下')
      return
    }

    const trimmedInput = inputText.trim()
    if (trimmedInput === '') {
      ElNotification.warning('消息不能为空')
      return
    }

    const message = {
      id: user.value.id,
      name: user.value.name,
      imageUrl: user.value.imageUrl,
      message: trimmedInput,
      type:type
    }

    websocket.value.send(JSON.stringify(message))
    input.value = ''
}


// let rec = null;
// const recwave = ref(null);
// let wave = null;

// // 定义录音状态
const mediaRecorder = ref(null);// 媒体录制器
const audioChunks = ref([]);// 音频片段
const audioUrl = ref('');// 音频URL
const recognition = ref(null);// 语音识别器
const transcript = ref('');// 识别结果
const errorMessage = ref('');// 错误信息
const isRecording = ref(false);// 是否正在录音
const isPaused = ref(false);// 是否暂停
const audioContext = ref(null);// 音频上下文
const analyser = ref(null);// 分析器
const source = ref(null);// 音频源
const animationId = ref(null);// 动画ID
const monitorVolumeInterval = ref(null);

// // 根据录音状态动态设置图标
const recordingIcon = ref(markRaw(Microphone));
const tooltipContent=ref("语音输入")
const toggleVoice = async () => {
  isRecording.value = !isRecording.value;

  if (!isRecording.value) {
    recordingIcon.value = Microphone;
    tooltipContent.value = "语音输入";
    stopRecording();
  } else {
    recordingIcon.value = Mic;
    tooltipContent.value = "停止语音输入";
    startRecording();
  }
};

/**
 * 启动录音
 * @returns {Promise<void>}
 */
 const startRecording = async () => {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    mediaRecorder.value = new MediaRecorder(stream);
    audioChunks.value = [];

    mediaRecorder.value.ondataavailable = (event) => {
      audioChunks.value.push(event.data);
    };

    mediaRecorder.value.onstop = () => {
      const audioBlob = new Blob(audioChunks.value, { type: 'audio/wav' });
      audioUrl.value = URL.createObjectURL(audioBlob);
    };

    mediaRecorder.value.start();
    startRecognition();

    audioContext.value = new (window.AudioContext || window.webkitAudioContext)();
    analyser.value = audioContext.value.createAnalyser();
    source.value = audioContext.value.createMediaStreamSource(stream);
    source.value.connect(analyser.value);

    // 启动音量检测
    // monitorVolumeInterval.value = monitorVolume();
  } catch (error) {
    console.error('获取麦克风权限失败:', error);
  }
};

const stopRecording = () => {
  if (mediaRecorder.value) {
    mediaRecorder.value.stop();
  }
  if (recognition.value) {
    recognition.value.stop();
  }
  if (audioContext.value && audioContext.value.state !== 'closed') {
    audioContext.value.close();
  }
  if (monitorVolumeInterval.value) {
    clearInterval(monitorVolumeInterval.value); // 清除定时器
    monitorVolumeInterval.value = null;
  }
  cancelAnimationFrame(animationId.value);
  isRecording.value = false;
  isPaused.value = false;
};
/**
 *  暂停录音
 */
 const pauseRecording = () => {
  if (mediaRecorder.value && isRecording.value) {
    mediaRecorder.value.pause();
    if (recognition.value) {
      recognition.value.stop();
    }
    isPaused.value = true;
  }
};

const resumeRecording = () => {
  if (mediaRecorder.value && isPaused.value) {
    mediaRecorder.value.resume();
    if (recognition.value) {
      startRecognition();
    }
    isPaused.value = false;
  }
};
/**
 * 检测麦克风音量
 */
 const monitorVolume = () => {
  const bufferLength = analyser.value.fftSize;
  const dataArray = new Uint8Array(bufferLength);

  const checkVolume = () => {
    analyser.value.getByteTimeDomainData(dataArray);
    let sum = 0;
    for (let i = 0; i < bufferLength; i++) {
      sum += (dataArray[i] - 128) * (dataArray[i] - 128);
    }
    const volume = Math.sqrt(sum / bufferLength);

    if (volume > 1) {
      isRecording.value = true;
      if (recognition.value && !isPaused.value && !isRecognitionActive) {
        startRecognition();
      }
    } else {
      isRecording.value = false;
    }
  };

  return setInterval(checkVolume, 100); // 每 100ms 检测一次
};

// 在 stopRecording 中清除定时器
// const stopRecording = () => {
//   if (mediaRecorder.value) {
//     mediaRecorder.value.stop();
//   }
//   if (recognition.value) {
//     recognition.value.stop();
//   }
//   if (audioContext.value && audioContext.value.state !== 'closed') {
//     audioContext.value.close();
//   }
//   clearInterval(monitorVolumeInterval.value); // 清除定时器
//   isRecording.value = false;
//   isPaused.value = false;
// };
/**
 * 启动语音识别
 */
let isRecognitionActive = false;

const startRecognition = () => {
  if (!isRecognitionActive) {
    recognition.value = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
    recognition.value.lang = 'zh-CN';
    recognition.value.continuous = true;
    recognition.value.interimResults = true;

    recognition.value.onresult = (event) => {
      let interimTranscript = '';
      for (let i = event.resultIndex; i < event.results.length; i++) {
        const transcriptPart = event.results[i][0].transcript;
        if (event.results[i].isFinal) {
          input.value += transcriptPart;
        } else {
          interimTranscript += transcriptPart;
        }
      }
    };

    recognition.value.onerror = (event) => {
      console.error('Recognition error:', event.error);
    };

    recognition.value.onend = () => {
      console.log('语音识别结束');
      isRecognitionActive = false;
      // 如果不是手动暂停，继续识别
      if (isRecording.value && !isPaused.value) {
        startRecognition();
      }
    };

    recognition.value.start();
    isRecognitionActive = true;
  }
};
/**
 * 停止录音
 */
//  const stopRecording = () => {
//   if (mediaRecorder.value) {
//     mediaRecorder.value.stop();
//   }
//   if (recognition.value) {
//     recognition.value.stop();
//   }
//   if (audioContext.value && audioContext.value.state !== 'closed') {
//     audioContext.value.close();
//   }
//   cancelAnimationFrame(animationId.value);
//   isRecording.value = false;
//   isPaused.value = false;
// };

onUnmounted(() => {
  if (audioContext.value && audioContext.value.state !== 'closed') {
    audioContext.value.close();
  }
  cancelAnimationFrame(animationId.value);
});

// 获取所有群组消息
const getAllGroupMessage = async () => {
  try {
    const result = await getAllGroupMessageAPI()
    messageList.value = result.data.data
    // console.log(result)
    // console.log(messageList.value)
  } catch (error) {
    ElNotification.error('获取消息失败')
  }
}

// 设置默认头像
const setDefaultImage = (event) => {
  event.target.src = 'https://p3fx.kgimg.com/v2/fxuserlogo/eac9145ecd909b9606c4f8e5f3e936e7.jpg_200x200.jpg'
}

// 处理窗口卸载事件
const handleBeforeUnload = () => {
  if (websocket.value && websocket.value.readyState === WebSocket.OPEN) {
    // console.log("33333333")
    websocket.value.close()
  }
}


// 组件挂载后执行的操作
onMounted(() => {
  if(counterStore.jwt){
    initSpeech()
    user.value=parseJwt(counterStore.jwt)
    console.log()
    login()
    getAllGroupMessage()
    scrollToBottom()
  // 添加窗口卸载事件监听器
  window.addEventListener('beforeunload', handleBeforeUnload)
  }else{
    websocket.value?.close()
    router.push('/')
  }

})

// 组件卸载时关闭WebSocket连接
onUnmounted(() => {
  websocket.value?.close()
  messageList.value = []

  // 移除窗口卸载事件监听器
  window.removeEventListener('beforeunload', handleBeforeUnload)
})

// 更新消息列表后滚动到底部
onUpdated(() => {
  scrollToBottom()
})

// 监听消息列表变化，更新在线人数
watch(messageList, (newList) => {
  newList.forEach(item => {
    if (item.id === 0) {
      setOnlineNum(item.name)
    }
  })
}, { deep: true, immediate: true })
</script>

<style>
.custom-dialog{
  /* background-color: yellowgreen !important; */
  border-radius: 15px !important;
}

.custom-dialog .el-dialog__header {
   display: none !important; 
}

.custom-dialog .el-dialog__headerbtn {
  display: none !important; 
}
.custom-dialog .el-dialog__body {
  width: 100%;
  height: 100%;
  /* overflow: hidden; */
  /* background-color: blue; */
  padding: 0 !important;
}
</style>
<style scoped>
:deep(.el-button){
  --el-button-active-border-color:rgba(255, 0, 0, 0);
}
/* 系统通知样式 */
.notice {
  text-align: center;
}
/* 图片样式 */
img {
  width: 100%;
  height: 100%;
}
/* 聊天室整体布局 */
.room {
  width: 100%;
  height: calc(100% - 40px);
  padding-top: 40px;
  display: flex;
  flex-direction: column;
}
/* 消息列表容器 */
.view {
  overflow: auto;
  width: 100%;
  height: calc(100% - 210px);
  background-color: rgb(227, 228, 227);
  /* background-color: rebeccapurple; */
}
/* 其他用户的消息样式 */
.other {
  margin: 10px;
  width: calc(100% - 30px);
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
}
/* 头像样式 */
.other .hImg {
  width: 35px;
  height: 35px;
  border-radius: 50%;
  margin-bottom: auto;
}
/* 消息内容样式 */
.other .message {
  position: relative;
  word-wrap: break-word;
  background-color: rgb(255, 255, 255);
  margin: 0 10px;
  border-radius: 6px;
  padding: 8px 30px 8px 12px;
  max-width: 300px;
  span{
    font-size: 13px;
    color: rgb(128, 128, 128);
    width: 200px;
    position: absolute;
    /* background-color: yellowgreen; */
    left: 105%;
    bottom: 0;
  }
}
/* 当前用户的消息样式 */
.me {
  margin: 10px;
  width: calc(100% - 30px);
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-end;
}
/* 当前用户头像样式 */
.me .hImg {
  width: 35px;
  height: 35px;
  border-radius: 50%;
  margin-bottom: auto;
}
/* 当前用户消息内容样式 */
.me .message {
  word-wrap: break-word;
  background-color: rgba(28, 199, 42, 0.808);
  margin: 0 10px;
  border-radius: 6px;
  padding: 8px 12px;
  position: relative;
  max-width: 300px;
  span{
    font-size: 13px;
    color: rgb(128,128,128);
    width: 200px;
    position: absolute;
    right: 80%;
    top: 50%;
  }
}
:deep(.play-btn){
  width: 40px;
  /* background-color: yellowgreen; */
  position: absolute;
  /* float: right; */
  right: 5px;
  bottom: 2px;
  /* align-items: end; */
}
.aite{
  /* width: 100%; */
  height: 30px;
  position: absolute;
  bottom: 210px;
  /* background-color: rgba(153, 205, 50, 0.288); */
}
.aiteItem{
  /* width: ; */
  background-color: rgba(28, 199, 42, 0.589);
  margin: 0 5px 0 5px;
  padding: 0 8px 0 8px;
  border-radius: 3px;
  font-size: small;
  cursor: pointer;
}
/* 输入框和按钮容器 */
.input {
  width: 100%;
  height: 220px;
  /* background-color: yellowgreen; */
  overflow: hidden;
}

/* Element Plus输入框内部样式 */
:deep(.el-textarea__inner) {
  outline: none;
  border: none;
  resize: none;
  box-shadow: none;
  /* background-color: yellow; */
}
  
.input-anniu {
    width: 50px;
    height: 50px;
    float: right;
    border-radius: 50%;
    margin-right: 20px;
    margin-bottom: 50px;
    /* padding-bottom: 20px; */
    /* position: absolute; */
    bottom: 0;
    font-size: 24px;
    color: #fff;
    background-color: #d6d5de;
  }
  
.bo{
  width: 40vh;
  aspect-ratio: 1/1;
  background-color: #ffffff;
  position:absolute;
  top:20%;
  left: 40%;
  border-radius: 50%;
  /* z-index: 9999; */
}

.recording-animation {
  
  position:absolute;
  top:30%;
  left: 40%;
  width: 25vh;
  aspect-ratio: 1/1;
    background-color: #F44336;
    border-radius: 50%;
    animation: pulse 1.2s infinite;
    margin: 20px auto;
    text-align: center;
    color: white;
    font-size: 34px;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 10px;
    cursor: pointer;
  }
  @keyframes pulse {
    0% {
      transform: scale(0.95);
      box-shadow:  0 0 0 10px rgba(255, 0, 0, 0.5);
    }
    70% {
      transform: scale(1);
      box-shadow: 0 0 0 20px rgba(255, 0, 0, 0);
    }
    100% {
      transform: scale(0.95);
      box-shadow: 0 0 0 0 rgba(255, 0, 0, 0);
    }
  }
</style>